package com.xnew.related;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import sun.misc.BASE64Encoder;

import java.io.IOException;
import java.io.InputStream;
import java.security.*;
import java.security.cert.CertificateException;

/**
 * 客户端签名
 * 
 * @author wd
 * 
 */
public class InitSign {

	// 证书密码
	private static String certPassword = "123456";

	// 待签名的字符串
	private static String signText = "123456";

	// 证书类型
	private static String certType = "PKCS12";

	public static String initHkSign(InputStream is, String certAlias) {

		String ret = null;

		try {
			if (is == null || is.available() < 1) {
				System.out.println("cert load error: cert is null or size 0.");
			}

			// Plug the Provider into the JCA/JCE
			Security.addProvider(new BouncyCastleProvider());

			KeyStore jks = KeyStore.getInstance(certType);
			// System.out.println("Create PKCS12 KeyStore Object.");

			jks.load(is, certPassword.toCharArray());
			// System.out.println("Load PKCS12 KeyStore ok.");

			PrivateKey privKey = (PrivateKey) jks.getKey(certAlias, certPassword.toCharArray());
			// System.out.println("get cert Private Key ok.");

			Signature rsa = Signature.getInstance("MD5withRSA", "BC");

			rsa.initSign(privKey);
			rsa.update(signText.getBytes());
			// System.out.println("init sign ok.");

			byte[] sig = rsa.sign();
			// System.out.println("sign ok.");

			ret = new BASE64Encoder().encode(sig);

		} catch (KeyStoreException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (CertificateException e) {
			e.printStackTrace();
		} catch (UnrecoverableKeyException e) {
			e.printStackTrace();
		} catch (NoSuchProviderException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (SignatureException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		}

		return ret;
	}

}
